package com.example.event_resource_java.sms.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.event_resource_java.authority.server.UserServer;
import com.example.event_resource_java.commons.domain.UserDO;
import com.example.event_resource_java.commons.enums.Constants;
import com.example.event_resource_java.commons.util.ApiResult;
import com.example.event_resource_java.sms.sender.AlySender;
import com.example.event_resource_java.starinside.redis.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @ClassName SmsController
 * @Description:
 * @Author: ak
 * @CreateDate: 2024/5/16 19:04
 * @UpdateUser:
 * @UpdateDate: 2024/5/16 19:04
 * @UpdateRemark:
 * @Version: 1.0
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private UserServer userServer;
    @Autowired
    private AlySender alySender;

    @GetMapping("/sendCode")
    @CrossOrigin
    @ApiOperation("发送验证码")
    public ApiResult sendCode(String mobile) {

        String code = new Random().nextInt(8999) + 1000 + "";
        String smsLimitKey = Constants.SMS_LIMIT_KEY + mobile;

        QueryWrapper<UserDO> userDOQueryWrapper = new QueryWrapper<>();
        userDOQueryWrapper.eq("mobile", mobile);
        UserDO userDO = this.userServer.getOne(userDOQueryWrapper);

        if (ObjectUtil.isNull(userDO)) {
            return ApiResult.fail("用户不存在 请联系管理员！");
        }

        // 非教师用户不能使用
        if (ObjectUtil.notEqual(userDO.getType(), 1)) {
            return ApiResult.success("忘记密码仅限教师用户使用!");
        }

        try {
            if (RedisUtil.hasKey(smsLimitKey)) {
                if ((Integer) RedisUtil.get(smsLimitKey) == 5) {
                    return ApiResult.fail("获取次数已达上限 请明天重试");
                } else {
                    RedisUtil.set(smsLimitKey, (Integer) RedisUtil.get(smsLimitKey) + 1, 24 * 60 * 60);
                }

            } else {
                RedisUtil.set(smsLimitKey, 1, 24 * 60 * 60);
            }

            alySender.send(mobile, code, "SMS_187952684");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String smsKey = Constants.SMS_CODE_KEY + mobile;
        // 存入redis
        RedisUtil.set(smsKey, code, 60 * 5);

        return ApiResult.success("发送成功");
    }
}
